<?php
/*
 * MiniMe - a minimalistic OStatus complient microblogging tool
 * Copyright (C) 2010, Tuomas Koski - koski.tuomas@gmail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @author     Tuomas Koski <koski.tuomas@gmail.com>
 * @copyright  Tuomas Koski
 * @license    http://www.gnu.org/licenses/lgpl.txt
 */
class Atom_Feed_Link implements Atom_ChildElement {
    
    private $href;
    private $type;
    private $rel;
    
    const REL_ALTERNATE = 'alternate';
    const TYPE_TEXTHTML = "text/html";
    
    const ELEMENT_LINK = "link";
    
    const ATTRIBUTE_REL  = "rel";
    const ATTRIBUTE_HREF = "href";
    const ATTRIBUTE_TYPE = "type";
    
    public function __construct($rel, $type, $href) {
        $this->setRel($rel);
        $this->setType($type);
        $this->setHref($href);
    }
    
    private function setRel($rel) {
        if(empty($rel)) {
            throw new Exception("Rel cannot be set empty.");
        }
        $this->rel = $rel;
    }
    
    private function setType($type) {
        // Type can be empty, check for example case hub:
        // <link href="http://lobstermonster.org/minime/hub.php" rel="hub"/>
        $this->type = $type;
    }
    
    private function setHref($href) {
        if(empty($href)) {
            throw new Exception("Href cannot be set empty.");
        }
        $this->href = $href;
    }
    
    public function getHref() {
        return $this->href;
    }
	
	/**
	 * This should return element similar to:
	 * <link rel="alternate" type="text/html" href="http://identi.ca/tkoski"/>
	 * 
     * @return DOMElement
     */
    public function asDomElement(DOMDocument $dom) {
        
        $element = $dom->createElement(self::ELEMENT_LINK);
        
        $element->setAttribute(self::ATTRIBUTE_REL, $this->rel);
        
        if(!empty($this->type)) {
            $element->setAttribute(self::ATTRIBUTE_TYPE, $this->type);
        } 
        
        $element->setAttribute(self::ATTRIBUTE_HREF, $this->href);
        
        return $element;
    }
    
    public static function buildFromDOMElement(DOMElement $elm) {
        $href = $elm->getAttribute("href");
        $type = $elm->getAttribute("type");
        $rel = $elm->getAttribute("rel");
        return new Atom_Feed_Link($rel, $type, $href);
    }
}